import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';
import ZImg from 'react-zmage'
import 'react-zmage/lib/zmage.css'
import find from 'lodash/find';
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem } from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import ReactDataGrid from 'react-data-grid';
import AddOrEditUser from './addOrEditUser';
import AddOrEditReserve from './addOrEditReserve';
import AddOrEditReserve2 from './addOrEditReserve2';
import AddOrEditStatus from './addOrEditStatus';
import request from '@/utils/request';

const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ engineering4, loading, global }) => ({
  engineering4,
  global,
  loading: loading.models.engineering4,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      users:[]
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      engineering4: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        engineering4: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'engineering4/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'engineering4/changeLoaded',
          });
          dispatch({
            type: 'engineering4/changeTableY',
          });
        },
      });

    }
    const that = this;
    // request(`/users`, {
    //   method: 'GET',
    //   params:{
    //     inspector:1,
    //     per_page:100
    //   }
    // }).then((response) => {
    //   if (response.status === 200) {
    //     that.setState({
    //       users: response.data.data,
    //     });
    //   }
    //
    // });
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'engineering4/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'engineering4/changeTableY',
    });
  };
  findChildFunc = (cb) => {
    this.file = cb;
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    const table = document.querySelector('.react-grid-Canvas');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'engineering4/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      engineering4: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem>
          {/*  <FormItem label="车牌号">
            {getFieldDecorator('license_plate_number', {
              initialValue: searchParams.license_plate_number,
            })(<Input style={{ width: '150px' }} placeholder="请输入"/>)}
          </FormItem>*/}
          {/*   <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>*/}
          {
            find(this.permissions, { name: 'car_operation' }) &&
            <Button
              type="primary"
              onClick={
                () => {
                  this.setState({
                    addModal: true,
                  });
                }
              }
            >
              新建项目申请
            </Button>
          }
        </FormItem>

      </Form>
    );
  }

  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    const state = this.AddForm.state;
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'engineering4/add',
      payload: {
        parameters:{
          ...formValues,
        },
        applicant_id:state.selectUser.id?state.selectUser.id:""
      },
      callback() {
        message.success('新建项目成功');
        that.setState({
          addModal: false,
        });
        const {
          engineering4: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const state = this.EditForm.state;
    const that = this;
    console.log('state.customJSON',state.customJSON)
    let meterskey=[]
    for(let i in formValues){
      let splitKey=i.split('-')
      let len=splitKey.length;
      if(len>=2){
        if(meterskey.indexOf(splitKey[1])<0){
          meterskey.push(splitKey[1])
        }
      }
    }
    const metersArr=[]
    for(let i=0;i<meterskey.length;i++){
      if(formValues[`name-${meterskey[i]}`]){
        metersArr.push({
          name:formValues[`name-${meterskey[i]}`],
          count:formValues[`count-${meterskey[i]}`],
          price:formValues[`price-${meterskey[i]}`],
          remark:formValues[`remark-${meterskey[i]}`],
        })
      }

    }
    console.log('metersArr',metersArr);

    let meterskey2=[]
    for(let i in formValues){
      let splitKey=i.split('-')
      let len=splitKey.length;
      if(len>=2){
        if(meterskey2.indexOf(splitKey[1])<0){
          meterskey2.push(splitKey[1])
        }
      }
    }
    const metersArr2=[]
    for(let i=0;i<meterskey2.length;i++){
      if(formValues[`schedule_number-${meterskey2[i]}`]){
        metersArr2.push({
          schedule_number:formValues[`schedule_number-${meterskey2[i]}`],
          schedule_task:formValues[`schedule_task-${meterskey2[i]}`],
          schedule_start:moment(formValues[`schedule_start-${meterskey2[i]}`]).format('YYYY-MM-DD'),
          schedule_end:moment(formValues[`schedule_end-${meterskey2[i]}`]).format('YYYY-MM-DD'),
          schedule_hours:formValues[`schedule_hours-${meterskey2[i]}`],
          schedule_menber:formValues[`schedule_menber-${meterskey2[i]}`],
        })
      }

    }
    console.log('metersArr2',metersArr2);
    let files=state.file_data.concat(state.file_data2)
    let status=''
    if(this.state.editRecord.status===5){
      status=6
    }
    this.props.dispatch({
      type: `engineering4/edit`,
      payload: {
        name:formValues.name,
        deadline_type:formValues.deadline_type,
        declare_nature:formValues.declare_nature,
        payable_amount:formValues.payable_amount,
        paid_amount:formValues.paid_amount,
        start_time:formValues.start_time?moment(formValues.start_time).format('YYYY-MM-DD'):'',
        end_time:formValues.end_time?moment(formValues.end_time).format('YYYY-MM-DD'):'',
        id: this.state.editRecord.id,
        files:files,
        status:status?status:this.state.editRecord.status,
        parameters:{
          ...state.customJSON,
          bill:metersArr,
          schedule:metersArr2
        },
      },
      callback() {
        message.success('修改项目成功');
        that.setState({
          editModal: false,
        });
        const {
          engineering4: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      license_plate_number:'',
      inspector_id:'',
      device_number:'',
      status:'',
      page: 1,
      per_page: 30,
    });
  };

  handleReserve=()=>{
    const formValues = this.ReserveForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const state = this.ReserveForm.state;
    console.log('start',state.start)
    console.log('end',state.end)
    let reviewer_ids=[]
    let replicator_ids=[]
    formValues.reviewer_ids.forEach(item => {
      reviewer_ids.push(item.key.split('#')[0]);
    })
    formValues.replicator_ids.forEach(item => {
      replicator_ids.push(item.key.split('#')[0]);
    })
    const that = this;
    request(`/car_applications`, {
      method: 'POST',
      data:{
        car_id:this.state.editRecord.id,
        cause:formValues.cause,
        reviewer_ids,replicator_ids,
        start_time:state.start,
        end_time:state.end
      }
    }).then((response) => {
      if (response.status === 200) {
        message.success('预定车辆成功');
        that.setState({
          reserveModal: false,
        });
        const {
          engineering4: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      }

    });

  }
  handleStatus=(id)=>{
    const that = this;
    request(`/projects/${id}`, {
      method: 'PUT',
      data:{
        status:8
      }
    }).then((response) => {
      if (response.status === 200) {
        message.success('验收成功');
        const {
          engineering4: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      }

    });
  }
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `engineering4/remove`,
      payload: { id },
      callback: () => {
        message.success('删除项目成功');
        const {
          engineering4: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  render() {
    const that = this;
    const {
      engineering4: { data, loading, tableY, meta, searchParams, selectedRowKeys },
      global: { gridTableW },
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {
            engineering4: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '立项原因',
        width: 160,
        frozen: true,
        key: 'name',
        formatter: (event) => {
          return <span title={event.row.parameters.lxyy}>{event.row.parameters.lxyy}</span>

        },
      },
      {
        name: '项目名称',
        width: 160,
        frozen: true,
        key: 'name2',
        formatter: (event) => {
          return <span title={event.row.name}>{event.row.name}</span>

        },
      },
      {
        name: '申请人',
        width: 120,
        frozen: true,
        key: 'applicant',
        formatter: (event) => {
          return event.row.applicant.name

        },
      },
      {
        name: '状态',
        width: 100,
        frozen: true,
        key: 'status',
        formatter: (event) => {

          const status=event.value;
          let status_text=''
          if(status===1){
            status_text='未提交'
          }else if(status===2){
            status_text='已提交'
          }else if(status===3){
            status_text='已立项'
          }else if(status===4){
            status_text='审批中'
          }else if(status===5){
            status_text='施工中'
          }else if(status===6){
            status_text='已施工'
          }else if(status===7){
            status_text='已验收'
          }else if(status===8){
            status_text='已完成'
          }

          return status_text;
        },
      },
      {
        name: '当前进度',
        width: 170,
        key: 'payable_amount',
        formatter: (event) => {
          return event.row.payable_amount?
            <span>
              <Progress percent={(Number(event.row.paid_amount)/Number(event.row.payable_amount)*100).toFixed(2)} />
              <span style={{position:'relative',left:'-38px'}}>{(Number(event.row.paid_amount)/Number(event.row.payable_amount)*100).toFixed(2)}%</span>
            </span>
            :''
        },
      },
      {
        name: '创建时间',
        width: 170,
        key: 'created_at',
      },
      {
        name: '提交时间',
        key: 'submit_time',
        width: 170,
      },

      {
        name: '操作',
        width: 300,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          {
            <Button
              type="primary"
              size="small"
              onClick={(e) => {
                this.setState({
                  editRecord: event.row,
                  editModal: true,
                });
              }
              }
            >管理
            </Button>
          }
          {
            event.row.status===6&&find(this.permissions, { name: 'project_acceptance' })&&
            <Button
              type="primary"
              icon="check"
              size="small"
              onClick={(e) => {
                confirm({
                  title: `确定要验收 ${event.row.name} 吗?`,
                  content: '请谨慎操作！',
                  okText: '确定',
                  okType: 'danger',
                  cancelText: '取消',
                  centered: true,
                  maskClosable: true,
                  onOk() {
                    that.handleStatus(event.row.id);
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });
              }
              }
            >验收
            </Button>
          }
        </Fragment>,
      },

    ].map(c => ({ ...defaultColumnProperties, ...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>在建项目</span>
      </div>
      <div className="table-page">
        {/*<div className="table-condition">{this.renderSimpleForm()}</div>*/}
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                this.props.dispatch({
                  type: 'engineering4/changeSelectRow',
                  payload: [row],
                });
              }
            }

          />
          {
            loading && <Loading/>
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }} meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.addModal} modalClass="addModal" title="新建项目申请"/>}
        className="addModal"
        visible={this.state.addModal}
        centered
        onCancel={() => {
          this.setState({ addModal: false });
        }}
        width={700}
        onOk={this.handleAdd}
      >
        <AddOrEditUser
          wrappedComponentRef={(inst) => this.AddForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={`查看`}/>}
        destroyOnClose
        visible={this.state.editModal}
        centered
        onOk={this.handleEdit}
        className="editModal"
        width={1000}
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ editModal: false, editRecord: {} });
        }}

      >
        <AddOrEditUser
          // type={'read'}
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EditForm = inst}/>
      </Modal>

      <Modal
        title={<BuildModalTitle visible={this.state.reserveModal} modalClass="reserveModal"
                                title={`预定 ${this.state.editRecord.license_plate_number}`}/>}
        destroyOnClose
        visible={this.state.reserveModal}
        centered
        onOk={this.handleReserve}
        className="reserveModal"
        width={1200}
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ reserveModal: false, editRecord: {} });
        }}

      >
        <AddOrEditReserve2
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.ReserveForm = inst}/>
      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.statusModal} modalClass="statusModal"
                                title={`车辆维护 ${this.state.editRecord.license_plate_number}`}/>}
        destroyOnClose
        visible={this.state.statusModal}
        centered
        onOk={this.handleStatus}
        className="statusModal"
        width={1200}
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ statusModal: false, editRecord: {} });
        }}

      >
        <AddOrEditStatus
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.StatusForm = inst}/>
      </Modal>
    </div>;
  }
}

export default BasicList;
